package com.zxl.live.tools.tools;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Calendar;
import java.util.Date;
import java.util.Formatter;
import java.util.Locale;

/**
 * 时间
 * Created by Administrator on 2015/11/5.
 */
public class TimeUtils {

    public static final int SECOND = 1000;

    public static final int MINUTE = 60 * SECOND;

    public static final int HOUR = 60 * MINUTE;

    public static final int DAY = 24 * HOUR;

    private static final int DEFAULT_PORT = 37;
    private static final String DEFAULT_HOST = "time-nw.nist.gov";

    /**
     * 获取美国时间
     * @return
     */
    public static Date getUsTimer() {
        Calendar calendar = Calendar.getInstance(Locale.US);
        return calendar.getTime();
    }

    public static Date getTimer() {
        Calendar calendar = Calendar.getInstance();
        return calendar.getTime();
    }

    /**
     * 获取当前时间戳（从服务器中获取会卡UI线程）
     * @return
     */
    public static long getServiceCurrentTimer() {
        InputStream raw = null;
        try {
            long differenceBetweenEpochs = 2208988800L;
            Socket theSocket = new Socket(DEFAULT_HOST, DEFAULT_PORT);
            raw = theSocket.getInputStream();
            long secondsSince1900 = 0;
            for (int i = 0; i < 4; i++) {
                secondsSince1900 = (secondsSince1900 << 8) | raw.read();
            }
            long secondsSince1970 = secondsSince1900 - differenceBetweenEpochs;
            return secondsSince1970 > 0 ? secondsSince1970 * 1000 : System.currentTimeMillis();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (raw != null) {
                try {
                    raw.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return System.currentTimeMillis();
    }

    public static String timeFormatString(int timeMs) {
        int totalSeconds = timeMs / 1000;

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours   = totalSeconds / 3600;
        StringBuilder formatBuilder = new StringBuilder();
        Formatter formatter = new Formatter(formatBuilder, Locale.getDefault());
        formatBuilder.setLength(0);
        if (hours > 0) {
            return formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return formatter.format("%02d:%02d", minutes, seconds).toString();
        }
    }

}
